import Cookies from 'js-cookie';
import { request } from '@inbiz/utils';
import { IntlFormatters } from 'react-intl';
import { RequestMethod } from 'umi-request';

export default class EformSelectFolderService {
  request: RequestMethod = request;
  remoteServer = {
    //第三方服务器， 用于文件摆渡
    url: '',
    token: '',
  };
  constructor(props: { intl: IntlFormatters; remoteServer?: { url: string; token: string } }) {
    // super(props);
    if (props.remoteServer && props.remoteServer.url) {
      this.remoteServer = {
        ...props.remoteServer,
        url:
          props.remoteServer.url[props.remoteServer.url.length - 1] === '/'
            ? props.remoteServer.url.slice(0, -1)
            : props.remoteServer.url,
      };
    } else {
      this.remoteServer = {
        url: '',
        token: this.remoteServer.token as string,
      };
    }
  }

  getTopFolders(params: {
    topFolderIds: number | number[];
    showEnterprise: boolean;
    showPerson: boolean;
    showTeam: boolean;
  }) {
    let args = {
      token: this.remoteServer.token,
      topFolderIds: params.topFolderIds,
      showEnterpriseFolder: params.showEnterprise,
      showPersonalFolder: params.showPerson,
      showTeamFolder: params.showTeam,
      permValue: 1,
      timestamp: new Date().getTime(),
    };
    return this.request(this.remoteServer.url + '/api/FolderRead/GetEdoc2FolderInfoByPage', {
      method: 'GET',
      params: args,
    }).then((res) => {
      res = [
        ...res.map((item: any) => {
          let data = {};
          Object.keys(item).forEach((key) => {
            if (key === 'Children' && item[key]?.length) {
              data[key.toLowerCase()] = item[key].map((v: any) => {
                let childrenData = {};
                Object.keys(v).forEach((key) => {
                  childrenData[key.toLowerCase()] = v[key];
                });
                return childrenData;
              });
            } else {
              data[key.toLowerCase()] = item[key];
            }
          });
          return data;
        }),
      ];
      return res;
    });
  }

  getFolderChilren(params: { folderid: number; pageNum: number; pageSize: number }) {
    let args = {
      token: this.remoteServer.token,
      topFolderId: params.folderid,
      pageNum: params.pageNum,
      pageSize: params.pageSize,
    };

    return this.request(this.remoteServer.url + '/api/FolderRead/GetChildrenFolderListByPage', {
      method: 'GET',
      params: args,
    }).then((res) => {
      let data = {};
      Object.keys(res).forEach((key) => {
        if (key === 'Children' && res[key]?.length) {
          data[key.toLowerCase()] = res[key].map((v: any) => {
            let childrenData = {};
            Object.keys(v).forEach((key) => {
              childrenData[key.toLowerCase()] = v[key];
            });
            return childrenData;
          });
        } else {
          data[key.toLowerCase()] = res[key];
        }
      });

      return data;
    });
  }

  getFileAndFolderChildren(params: { folderid: number; pageNum: number; pageSize: number }) {
    // basic:name 名称
    // basic:code 编号
    // basic:size 大小
    // basic:creator 创建人
    // basic:editor 修改人
    // basic:modifyTime 修改时间
    // basic:createTime 创建时间
    // basic:state 状态
    // basic:version 版本
    // basic:remark 备注
    // basic:securityLevel 密级
    let args = {
      folderId: params.folderid,
      pageNum: params.pageNum,
      pageSize: params.pageSize,
      sortField: 'basic:name',
      sortDesc: false,
      token: Cookies.get('token'),
    };

    return this.request(this.remoteServer.url + '/api/services/Doc/GetFileAndFolderList', {
      method: 'GET',
      params: args,
    }).then((res) => {
      let resData: any[] = [];
      if (res.result == 0) {
        resData = [
          ...res.data.FoldersInfo.map((item: any) => {
            let data = {};
            Object.keys(item).forEach((key) => {
              data[key.toLowerCase()] = item[key];
            });
            return data;
          }),
          ...res.data.FilesInfo.map((item: any) => {
            let data = {};
            Object.keys(item).forEach((key) => {
              data[key.toLowerCase()] = item[key];
            });
            return data;
          }),
          res.data.Settings.TotalCount,
        ];
      }
      return resData;
    });
  }

  getFolderChildrenFiles(params: { folderId: number; pageSize: number; pageNum: number }) {
    let args = {
      token: this.remoteServer.token,
      folderId: params.folderId,
      pageSize: params.pageSize,
      pageNum: params.pageNum,
      sortField: 'FileName',
      sortDesc: false,
      onlyShowFileType: '',
    };
    return this.request(this.remoteServer.url + '/api/FileRead/GetChildFileListPageByFolderId', {
      method: 'POST',
      params: args,
    });
  }

  searchFolderChildrenFiles(params: {
    folderId: number;
    pageSize: number;
    pageNum: number;
    keyword: string;
  }) {
    let args = {
      token: this.remoteServer.token,
      folderId: params.folderId,
      pageSize: params.pageSize,
      pageNum: params.pageNum,
      fileName: params.keyword,
      recursive: true,
    };
    return this.request(
      this.remoteServer.url + '/api/FileRead/GetChildFileListPageByFolderIdAndFileName',
      {
        method: 'POST',
        params: args,
      },
    );
  }

  searchFolderChildrenFolders(params: {
    folderId: number;
    pageNum: number;
    pageSize: number;
    keyword: string;
  }) {
    let args = {
      mnId: 0,
      docViewId: 0,
      argsXml: `<GetListArgs><PageNum>${params.pageNum}</PageNum><PageSize>${params.pageSize}</PageSize></GetListArgs>`,
      metaDataSearch: false,
      startNum: 0,
      searchType: 'MetaFolder',
      searchLocation: 'enterprise',
      // searchXml: `{"from":0,"size":99,"sort":[{"_score":{"order":"asc"}}],"query":{"query_string":{"query":"folderpath:(${params.folderId}) AND (foldername:(${params.keyword}) OR foldername:*${params.keyword}*)","default_operator":"AND"}}}`,
      searchXml: `{"from":0,"size":9999,"_source":{"excludes":["filecontent"]},"sort":[{"_score":{"order":"desc"}}],"query":{"query_string":{"query":" NOT folderid:1  AND foldername:(${params.keyword}) AND folderpath:(${params.folderId})","default_operator":"AND"}},"highlight":{"fields":{"foldername":{}},"pre_tags":"<span class='Highlighter'>","post_tags":"</span>","number_of_fragments":3,"no_match_size":250}}`,
    };
    return this.request(this.remoteServer.url + '/api/FolderRead/GetMapSearchFolderResultList', {
      method: 'POST',
      data: args,
      requestType: 'form',
    });
  }
  getHotWordsList(params: {
    keyword: string;
    type: number;
    curFolderId: number;
    searchLocation: string;
  }) {
    let args = {
      ...params,
      fun: 'GetHotWordsList',
      module: 'WebClient',
    };
    return this.request(this.remoteServer.url + '/WebCore', {
      requestType: 'form',
      method: 'POST',
      data: args,
    });
  }
  SaveSearchData(params: { keyWord: string }) {
    let args = {
      ...params,
      fun: 'SaveSearchData',
      module: 'MetaDataManager',
    };
    return this.request(this.remoteServer.url + '/WebCore', {
      requestType: 'form',
      method: 'POST',
      data: args,
    });
  }
  GetFolderById(params: { folderId: number }) {
    let args = {
      ...params,
      module: 'WebClient',
      fun: 'GetFolderById',
    };
    return this.request(this.remoteServer.url + '/WebCore', {
      requestType: 'form',
      method: 'POST',
      data: args,
    });
  }
}

export async function getDocumentInfoByFile(docmentIds: string, props: any) {
  let url = `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/control/getDocumentInfo`;
  if (props.childModelConfig) {
    url = `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/business/selectDatas`;
  }
  if (docmentIds && !props.childModelConfig) {
    return request
      .post(url, {
        data: [
          {
            docmentIds,
            docType: '1',
          },
        ],
      })
      .then((res) => {
        let arr = res.data?.FileInfoList?.map((item: any) => {
          let data = {};
          Object.keys(item).forEach((key) => {
            data[key.toLowerCase()] = item[key];
          });
          return data;
        });
        return arr;
      });
  } else if (props.childModelConfig) {
    return request
      .post(url, {
        data: {
          name: props.storageConfig.name,
          data: {
            ref_id: props.inbiz?.queryData?.id,
            controlid: props.controlId,
          },
        },
      })
      .then((res) => {
        const list: Array<any> = res?.data ?? [];
        const result = list.map((ele) => ({
          // id: ele.id,
          // fileid: ele.fileid,
          // filename: ele.filename,
          // status: 'upload successful',
          // filelastsize: ele.filelastsize,
          ...ele,
        }));
        return result;
      });
  } else {
    return {
      data: {
        FolderInfoList: [],
        FileInfoList: [],
      },
      dataDescription: '',
      message: '',
      result: 0,
    };
  }
}

export async function getDocumentInfoByFolder(docmentIds: string, props: any) {
  const host = props?.remoteServer?.url
    ? props.remoteServer.url[props.remoteServer.url.length - 1] === '/'
      ? props.remoteServer.url.slice(0, -1)
      : props.remoteServer.url
    : '';
  let url =
    host + `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/control/getDocumentInfo`;

  if (props.childModelConfig) {
    url = `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/business/selectDatas`;
  }
  if (docmentIds && !props.childModelConfig) {
    return (
      !host
        ? request.post(url, {
            data: [
              {
                docmentIds,
                docType: '0',
              },
            ],
          })
        : fetch(url + '?token=' + props.remoteServer.token, {
            method: 'POST',
            body: JSON.stringify([
              {
                docmentIds,
                docType: '0',
              },
            ]),
          }).then((res) => res.json())
    ).then((res) => {
      let arr = res.data?.FolderInfoList?.map((item: any) => {
        let data = {};
        Object.keys(item).forEach((key) => {
          data[key.toLowerCase()] = item[key];
        });
        return data;
      });
      return arr;
    });
  } else if (props.childModelConfig) {
    return request
      .post(url, {
        data: {
          name: props.storageConfig.name,
          data: {
            ref_id: props.inbiz?.queryData?.id,
            controlid: props.controlId,
          },
        },
      })
      .then((res) => {
        const list: Array<any> = res?.data ?? [];
        const result = list.map((ele) => ({
          ...ele,
          // id: ele.id,
          // fileid: ele.fileid,
          // filename: ele.filename,
          // status: 'upload successful',
          // filelastsize: ele.filelastsize,
        }));
        return result;
      });
  } else {
    return {
      data: {
        FolderInfoList: [],
        FileInfoList: [],
      },
      dataDescription: '',
      message: '',
      result: 0,
    };
  }
}
